package org.zachary.agent.infrastructure.utils;



import javax.crypto.SecretKey;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * JWT工具类（支持自动续期+Redis集成）
 * 依赖：jjwt-api 0.12.5 + Spring Data Redis
 */
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.zachary.agent.domain.aggregate_model.token.DeviceId;
import org.zachary.agent.infrastructure.exception.JwtUtilException;

import static org.zachary.agent.infrastructure.utils.AgentTime.ACCESS_EXPIRE_TIME;
import static org.zachary.agent.infrastructure.utils.AgentTime.REFRESH_EXPIRE_TIME;

/**
 * @author Zachary
 * @version 1.0
 * @time 2025-04-01
 */
@Slf4j
@Component
public class JwtUtil {

    /** 使用HS512加密算法 签名 */
    static SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS512);

    /** 设置token过期时间 */
    private static final long EXPIRE_TIME = 1000*2*60;

    /**
     * 创建token
     * @param uuid
     * @return
     */
    // JwtUtil.java - 统一使用UTC时间
    public static String createAccessToken(String uuid) {
        Instant now = Instant.now(); // UTC时间
        Instant exp = now.plus(ACCESS_EXPIRE_TIME, ChronoUnit.MILLIS);

        return Jwts.builder()
                .claim("uuid", uuid)
                .setIssuedAt(Date.from(now))
                .setExpiration(Date.from(exp)) // UTC时间
                .signWith(key)
                .compact();
    }
    public static String createRefreshToken(String uuid, DeviceId device){
        return Jwts.builder()
                .claim("uuid", uuid)
                .claim("device", device)
                .signWith(key)
                .setSubject("AUTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + REFRESH_EXPIRE_TIME))
                .compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Claims  parseToken(String token){
        //顺带说一句，当Jwt设置了有效期，有效期时间过了之后也会抛出异常，解决办法是try
        //catch一下，将异常抛给统一异常处理类
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims;
        } catch (ExpiredJwtException  eje) {
            log.error("===== Token过期 =====", eje);
            throw new JwtUtilException(eje.getMessage());
        } catch (Exception e){
            log.error("===== token解析异常 =====", e);
            throw new JwtUtilException(e.getMessage());
        }
    }

    /**
     * 获取用户id
     * @param token
     * @return
     */
    public static String getUserId(String token){
        return parseToken(token).get("uuid").toString();
    }

    /**
     * 获取用户名
     * @param token
     * @return
     */
    public static String getDeviceId(String token){
        return (String)parseToken(token).get("device");
    }

    /**
     * 判断是否过期
     * @param token
     * @param base64Security
     * @return
     */
    public static boolean isExpiration(String token, String base64Security) {
        return parseToken(token).getExpiration().before(new Date());
    }
    // JwtUtil.java - 允许30秒时间偏差
    public static boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey(key)
                    .setAllowedClockSkewSeconds(30) // 允许30秒偏差
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (ExpiredJwtException e) {
            log.error("JWT已过期: {}", e.getMessage());
        } catch (Exception e) {
            log.error("JWT验证失败: {}", e.getMessage());
        }
        return false;
    }
}
